﻿/// <reference path="vswd-ext_2.2.js" />


function showRouteWindow(){
    var ftimer;
    var ttimer;
    var fromLoading = false;
    var toLoading = false;
    var fstore = new Ext.data.ArrayStore({
        fields: ['id','val','lat','lng'],
        data: []
    });
    
    var tstore = new Ext.data.ArrayStore({
        fields: ['id','val','lat','lng'],
        data: []
    });

    var panResult = new Ext.Panel({
        title: _RouteSearch_Result,
        region: 'center',
        width: 500,
        autoScroll: true
    });
	
	
	var cmbfrom = new Ext.form.ComboBox({
	    fieldLabel:_RouteSearch_From,
	    //disableKeyFilter: true,
	    triggerAction:'all',
	    //clearFilterOnReset:true,
	    mode:'local',
	    labelStyle:"padding-left:6px",
	    store: fstore,
	    valueField:'id',
        displayField:'val',
        //autoSave:false,
	    width:300
	});

	function getFromAddresses(nameArray, latiArray, longiArray) {
	    var i;
	    if (nameArray) {
	        fstore.removeAll();
	        for (i = 0; i < nameArray.length; i++) {
	            var d = new Object();
	            d.val = nameArray[i];
	            d.id = i.toString();
	            d.lat = latiArray[i];
	            d.lng = longiArray[i];
	            var records = new Ext.data.Record(d)
	            fstore.add(records);
	        }
	        cmbfrom.expand();
	    }
	}
	
//	function getFromAddresses(layer, resultsArray, places, hasMore, veErrorMessage) {
//	    var i;
//	    if (places) {
//	        fstore.removeAll();
//	        for (i = 0; i < places.length; i++) {
//	            var d = new Object();
//	            d.val = places[i].Name;
//	            d.id = i.toString();
//	            d.lat = places[i].LatLong.Latitude;
//	            d.lng = places[i].LatLong.Longitude;
//	            var records = new Ext.data.Record(d)
//	            fstore.add(records);
//	        }
//	        cmbfrom.expand();
//	    }
	//	}

	function getToAddresses(nameArray, latiArray, longiArray) {
	    var i;
	    if (nameArray) {
	        tstore.removeAll();
	        for (i = 0; i < nameArray.length; i++) {
	            var d = new Object();
	            d.val = nameArray[i];
	            d.id = i.toString();
	            d.lat = latiArray[i];
	            d.lng = longiArray[i];
	            var records = new Ext.data.Record(d)
	            tstore.add(records);
	        }
	        cmbto.expand();
	    }
	}
	
//	function getToAddresses(layer, resultsArray, places, hasMore, veErrorMessage) {
//	    var address = null;
//	    var i;
//	    if (places) {
//	        tstore.removeAll();
//	        for (i = 0; i < places.length; i++) {
//	            var d = new Object();
//	            d.val = places[i].Name;
//	            d.id = i.toString();
//	            d.lat = places[i].LatLong.Latitude;
//	            d.lng = places[i].LatLong.Longitude;
//	            var records = new Ext.data.Record(d)
//	            tstore.add(records);
//	        }
//	        cmbto.expand();
//	    }

//	}
/*phu comment
	cmbfrom.addListener('keyup', function(obj) {
	    if (ftimer != null)
	        window.clearTimeout(ftimer);

	    ftimer = window.setTimeout(function() {
	            imap.findAddress(cmbfrom.getRawValue(),getFromAddresses);
//	        var mapsearch = new GMapExtentSearch(imap.map, function(resultArray, latArray, lngArray) {
//	            fromLoading = true;
//	            fstore.removeAll();
//	            var i;
//	            for (i = 0; i < resultArray.length; i++) {
//	                var d = new Object();
//	                d.val = resultArray[i];
//	                d.lat = latArray[i];
//	                d.lng = lngArray[i];
//	                d.id = i.toString();
//	                var records = new Ext.data.Record(d)
//	                fstore.add(records);
//	            }

//	            cmbfrom.expand();
//	            fromLoading = false;
//	        });
//	        mapsearch.execute(cmbfrom.getRawValue());
//	    }, 3000) : setTimeout(function() {
//	        imap.map.Find("", cmbfrom.getRawValue(), null, null, 0, 10, true, true, true, true, getFromAddresses);
	    }, 3000);

	});
*/   
	var cmbto = new Ext.form.ComboBox({
	    fieldLabel:_RouteSearch_To,
	    labelStyle:"padding-left:6px",
	    //disableKeyFilter: true,
	    triggerAction:'all',
	    //clearFilterOnReset:true,
	    mode:'local',
	    store: tstore,
        valueField:'id',
        displayField:'val',
        //autoSave:false,
	    width:300
	});
	cmbto.addListener('keyup', function(el,e) {		
		if(e.keyCode == 13){
			panResult["body"].dom.innerHTML="";
			findRoute();
		}
/*phu comment
	    if (ttimer != null)
	        window.clearTimeout(ttimer);
	        ttimer = window.setTimeout(function() {
	            imap.findAddress(cmbto.getRawValue(),getToAddresses);
	        }, 3000);
//	    ttimer = ftimer = (meimaptype == 0) ? window.setTimeout(function() {
//	        var mapsearch = new GMapExtentSearch(imap.map, function(resultArray, latArray, lngArray) {
//	            toLoading = true;
//	            tstore.removeAll();
//	            var i;
//	            for (i = 0; i < resultArray.length; i++) {
//	                var d = new Object();
//	                d.val = resultArray[i];
//	                d.lat = latArray[i];
//	                d.lng = lngArray[i];
//	                d.id = i.toString();
//	                var records = new Ext.data.Record(d)
//	                tstore.add(records);
//	            }
//	            cmbto.expand();
//	            toLoading = false;
//	        });
//	        mapsearch.execute(cmbto.getRawValue());
//	    }, 3000) : setTimeout(function() {
//	        imap.map.Find("", cmbto.getRawValue(), null, null, 0, 10, true, true, true, true, getToAddresses);
//	    }, 2000);
*/
	});
	function findRoute() {
	    if (fromLoading || toLoading) {
	        window.setTimeout('findRoute()');
	    }
	    else {
	        var from = cmbfrom.getRawValue();
	        var to = cmbto.getRawValue();
	        if (!isNaN(from) && from.toString().length > 0)
	            from = "(" + fstore.getAt(from).get('lat') + "," + fstore.getAt(from).get('lng') + ")";
	        if (!isNaN(to) && to.toString().length > 0)
	            to = "(" + tstore.getAt(to).get('lat') + "," + tstore.getAt(to).get('lng') + ")";

	        if (imap != null) {
	            var gpslang = getCookie("gpslang");
	            if (gpslang != null)
	                imap.findDirection(from, to, panResult["body"].dom, gpslang, fnload, fnerror);
	            else {
	                imap.findDirection(from, to, panResult["body"].dom, clientlang, fnload, fnerror);
	            }
	        }
	    }
	}
	
	var win = new Ext.Window({
	    title: _RouteSearch_Title,
	    width: 500,
	    height: 500,
	    layout: "border",
	    constrain:true,
	    items: [
			    {
			        xtype: "panel",
			        bodyStyle: "padding-top:5px",
			        title: _RouteSearch_Route,
			        width: 500,
			        height: 130,
			        layout: "form",
			        region: 'north',
			        buttonAlign: "right",
			        items: [
					    cmbfrom,
					    cmbto
				    ],
			        buttons: [{
			            text: _RouteSearch_Route,
			            handler: function() {
							panResult["body"].dom.innerHTML="";
			                findRoute();
			            }
			        },
				              {
				                  text: _RouteSearch_Clear,
				                  handler: function() {
				                      cmbfrom.setValue("");
				                      cmbto.setValue("");
									  panResult["body"].dom.innerHTML="";
				                      if (imap != null)
				                          imap.clearDirection();
				                  }
				              }
				              ]
			    }, panResult

		    ]
	});
    
    win.show();



    function fnload(directions) {
        var earthPolyLineVertex = [];
        for (var i = 0; i < directions.getPolyline().getVertexCount(); i++) {
            earthPolyLineVertex.push(this.realLatLngToMapLatLng(directions.getPolyline().getVertex(i)));
        }
        meiEarth.ShowDirectionInEarth(earthPolyLineVertex);
    }
    
    function fnerror(code){
        if(code<0){
            if (code == -1)
			    alert(_RouteSearch_ErrorAddress + code);
		    else if (code == -2)
			    alert(_RouteSearch_ErrorServer + code);
    			
		    else if (code == -3)
			    alert(_RouteSearch_ErrorMissing + code);
		    else if (code == -4)
			    alert(_RouteSearch_ErrorKey + code);

		    else if (code == -5)
			    alert(_RouteSearch_ErrorRequest + code);
		    else 
		        alert(_RouteSearch_ErrorUnknown);
        }
    }
}